import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';
import FileSaver from 'file-saver';

// 模拟 tansParams 函数，将对象转换为 URL 编码的字符串
function tansParams(params: any) {
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + '=';
    if (value !== null && value !== undefined) {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== undefined) {
            const params = propName + '[' + key + ']';
            const subPart = encodeURIComponent(params) + '=' + encodeURIComponent(value[key]);
            result += (subPart + '&');
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result.slice(0, -1);
}

// 模拟 blobValidate 函数，简单判断响应是否为登录相关内容（可按需调整）
function blobValidate(data: Blob) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const text = e.target?.result as string;
        const json = JSON.parse(text);
        // 假设登录相关响应包含特定字段，这里可按需调整判断逻辑
        resolve(!json.hasOwnProperty('login'));
      } catch (error) {
        resolve(true);
      }
    };
    reader.readAsText(data);
  });
}

const instance = axios.create({
  baseURL: 'http://localhost:9090/myAdminSystem', // 统一API前缀，支持多模块
  timeout: 10000,
});

let downloadLoadingInstance: any;

// 请求拦截器：有操作自动续期
instance.interceptors.request.use(
  config => {
    localStorage.setItem('tokenTime', Date.now().toString());
    return config;
  },
  error => Promise.reject(error)
);

// 通用下载方法
 export function download(url: string, params: any, fileName: string) {
  downloadLoadingInstance = MessagePlugin.success('正在下载数据，请稍候');
  return instance.post(url, params, {
    transformRequest: [
      (params: any) => {
        return tansParams(params);
      }
    ],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob'
  }).then(async (resp: any) => {
    const isLogin = await blobValidate(resp.data);
    if (isLogin) {
      const blob = new Blob([resp.data]);
      FileSaver.saveAs(blob, fileName);
    } else {
      const resText = await resp.data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = rspObj.msg || '下载文件失败';
      MessagePlugin.error(errMsg);
    }
    // info 没有 close 方法，这里无需关闭
  }).catch((r: any) => {
    console.error(r);
    MessagePlugin.error('下载文件出现错误，请联系管理员！');
    // info 没有 close 方法，这里无需关闭
  });
}

export default instance;